package com.chris.core.socket.netty.code;

import com.chris.core.socket.netty.dto.SocketParameterEnum;
import com.chris.core.socket.netty.dto.protocol.CustomMessageProtocol;
import com.chris.core.socket.netty.util.NettyRunTimeUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 自定义 - 编码器
 * 只面向java to java
 * 只合适此存在单一编解码的情况（不支持多编解码）
 * 2023-5-16
 */
public class CustomMessageEncoder extends MessageToByteEncoder<CustomMessageProtocol> {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 重载编码类
     * @param ctx           the {@link ChannelHandlerContext} which this {@link MessageToByteEncoder} belongs to
     * @param msg           the message to encode
     * @param out           the {@link ByteBuf} into which the encoded message will be written
     * @throws Exception
     */
    @Override
    protected void encode(ChannelHandlerContext ctx, CustomMessageProtocol msg, ByteBuf out) throws Exception {
        //long beginTime=System.currentTimeMillis();
        out.writeInt(msg.getType());
        out.writeInt(msg.getLen());
        out.writeBytes(msg.getByteContent());
        //在这里做流量限制不起作用，因为只是写入缓存，并未真正发出
        //if(msg.getType()== SocketParameterEnum.FileObjectType.getCode()) {
            //限流 10240 b/ms = 10240kb/s = 10m/s(实际7m/s)  , 5120 = 5m/s(实际3m/s)
        //    NettyRunTimeUtil.flowControl(msg.getLen(), beginTime, 1240);
       // }
    }


}
